package com.example.administrator.im.adapter;

import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.administrator.im.MyApplication;
import com.example.administrator.im.R;
import com.example.administrator.im.config.ImageConfig;
import com.example.administrator.im.data.IMData;
import com.example.administrator.im.db.FriendDBHelper;
import com.example.administrator.im.db.UserDBHelper;
import com.example.administrator.im.ui.activity.ShowImageActivity;
import com.example.administrator.im.utils.DisplayUtils;
import com.example.administrator.im.utils.DownloadImageUtils;
import com.example.administrator.im.utils.EMUtils;
import com.example.administrator.im.utils.FileUtils;
import com.example.administrator.im.utils.HttpUtils;
import com.hyphenate.chat.EMMessage;

import org.litepal.LitePal;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * create:2018/9/25 19:10
 * author: 姚鸿杰
 **/
public class ChatRoomAdapter extends RecyclerView.Adapter<ChatRoomAdapter.Holder> {

    private List<IMData> mList;
    private Context mContext;

    public ChatRoomAdapter(List<IMData> mList, Context mContext) {
        if (mList != null) {
            this.mList = mList;
        } else {
            this.mList = new ArrayList<>();
        }
        this.mContext = mContext;
    }

    public void addMsg(IMData data) {
        mList.add(data);
        notifyItemInserted(getItemCount() - 1);
    }

    @NonNull
    @Override
    public Holder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(mContext).inflate(R.layout.recycler_msg, viewGroup, false);
        return new Holder(v);
    }


    private void startIntent(View v, String url) {
        Intent intent = new Intent(mContext, ShowImageActivity.class);
        intent.putExtra("imgPath", url);
        mContext.startActivity(intent, ActivityOptions.makeSceneTransitionAnimation((Activity) mContext, v, "showImage").toBundle());
    }

    private Bitmap bitmap;
    private final int LEFT = 1;
    private final int RIGHT = 2;

    private void saveImage(String url, File file, int size) {
        if (!file.exists()) {
            DownloadImageUtils downloadImage = new DownloadImageUtils(url, MyApplication.getmContext(), size, size, file, new DownloadImageUtils.ImagedownLoadCallBack() {
                @Override
                public void onDownLoadSuccess(final File file) {
                }

                @Override
                public void onDownLoadFailed() {
                }
            });
            new Thread(downloadImage).start();
        }
    }

    @Override
    public void onBindViewHolder(@NonNull Holder holder, int position) {
        IMData item = mList.get(position);
        final EMMessage msg = item.getMsg();

        final String content = EMUtils.getContent(msg);

        int size = DisplayUtils.dip2px(mContext, 150);
        int headImgSize = ImageConfig.getItemSmall();
        String filePath = "";
        String fileName = "";

        //表示接收消息
        if (item.getMsg().direct() == EMMessage.Direct.RECEIVE) {
            holder.rightLayout.setVisibility(View.GONE);
            holder.leftLayout.setVisibility(View.VISIBLE);

            FriendDBHelper friend = LitePal.where("username = ?", msg.getUserName()).findFirst(FriendDBHelper.class);
            String url = HttpUtils.PORT + friend.getImg_path();

            //加载头像
            RequestOptions options = new RequestOptions()
                    .placeholder(R.mipmap.login_logo)
                    .error(R.mipmap.login_logo)
                    .override(headImgSize, headImgSize);
            Glide.with(mContext).load(url).apply(options).into(holder.left_civ);

            int what = msg.getIntAttribute("type", -1);
            if (what == EMUtils.TEXT) {
                holder.iv_left_img.setVisibility(View.GONE);
                holder.left_tv.setVisibility(View.VISIBLE);
                holder.left_tv.setText(content);
            } else if (EMUtils.IMAGE == what) {
                holder.iv_left_img.setVisibility(View.VISIBLE);
                holder.left_tv.setVisibility(View.GONE);
                RequestOptions options_img = new RequestOptions()
                        .placeholder(R.mipmap.login_logo)
                        .error(R.mipmap.login_logo).override(size, size);

                Glide.with(mContext).load(content).apply(options_img).into(holder.iv_left_img);

//                String[] split = content.split("/");
//                String imageName = split[split.length - 1];
//
//
//                filePath = mContext.getExternalCacheDir() + File.separator + "ChatRoomImages";
//                fileName = imageName + ".png";
                File mFile = FileUtils.getFilePath(content, FileUtils.CHAT_ROOM_PACK);

                //size 为考虑原图的情况
                saveImage(content, mFile, size);
            }

            final String finalFileName = fileName;
            final String finalFilePath = filePath;
            holder.iv_left_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startIntent(v, finalFilePath + "/" + finalFileName);
                }
            });

        } else { //表示发送消息

            holder.leftLayout.setVisibility(View.GONE);
            holder.rightLayout.setVisibility(View.VISIBLE);

            UserDBHelper user = LitePal.where("username = ?", msg.getFrom()).findFirst(UserDBHelper.class);
            String url = HttpUtils.PORT + user.getImg_path();

            //加载头像
            RequestOptions options = new RequestOptions()
                    .placeholder(R.mipmap.login_logo)
                    .error(R.mipmap.login_logo)
                    .override(headImgSize, headImgSize);
            Glide.with(mContext).load(url).apply(options).into(holder.right_civ);

            int what = msg.getIntAttribute("type", -1);
            if (what == EMUtils.TEXT) {
                holder.iv_right_img.setVisibility(View.GONE);
                holder.right_tv.setVisibility(View.VISIBLE);
                holder.right_tv.setText(EMUtils.getContent(item.getMsg()));
            } else {
                holder.iv_right_img.setVisibility(View.VISIBLE);
                holder.right_tv.setVisibility(View.GONE);

                RequestOptions options_img = new RequestOptions()
                        .placeholder(R.mipmap.login_logo)
                        .error(R.mipmap.ic_launcher).override(size, size);

                Glide.with(mContext).load(EMUtils.getContent(msg)).apply(options_img).into(holder.iv_right_img);
            }


            holder.iv_right_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startIntent(v, content);
                }
            });

        }
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public class Holder extends RecyclerView.ViewHolder {

        private ViewGroup leftLayout;
        private ViewGroup rightLayout;

        private CircleImageView left_civ;
        private CircleImageView right_civ;

        private ImageView iv_left_img;
        private ImageView iv_right_img;

        private TextView left_tv;
        private TextView right_tv;

        public Holder(@NonNull View itemView) {
            super(itemView);

            leftLayout = itemView.findViewById(R.id.left_msg);
            rightLayout = itemView.findViewById(R.id.right_msg);

            left_civ = itemView.findViewById(R.id.left_civ);
            right_civ = itemView.findViewById(R.id.right_civ);

            iv_left_img = itemView.findViewById(R.id.iv_left_img);
            iv_right_img = itemView.findViewById(R.id.iv_right_img);

            left_tv = itemView.findViewById(R.id.tv_left_content);
            right_tv = itemView.findViewById(R.id.tv_right_content);
        }
    }
}
